package com.example.administrator.officeplatform.Activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.administrator.officeplatform.Audit.AuditActivity;
import com.example.administrator.officeplatform.Audit.AuditAdapter;
import com.example.administrator.officeplatform.Audit.AuditDetailActivity;
import com.example.administrator.officeplatform.Audit.MyFQAdapter;
import com.example.administrator.officeplatform.Audit.SettlementAuditActivity;
import com.example.administrator.officeplatform.MyApplication;
import com.example.administrator.officeplatform.R;
import com.example.administrator.officeplatform.base.BaseActivity;
import com.example.administrator.officeplatform.bean.ReimbursementVoInfo;
import com.example.administrator.officeplatform.kj.IpUtil;
import com.example.administrator.officeplatform.utils.JsonUtil;
import com.example.administrator.officeplatform.utils.SwipeRefreshLayout;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyFQActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener{
    @Bind(R.id.tab_cost)
    RelativeLayout rl_cost;//费用成本按钮
    @Bind(R.id.tab_evection)
    RelativeLayout rl_evection;//差旅
    @Bind(R.id.tab_reward)
    RelativeLayout rl_reward;//奖励扣款
    @Bind(R.id.tab_overnight_money)
    RelativeLayout rl_overnight_money;//暂借款
    @Bind(R.id.tab_statement)
    RelativeLayout rl_statement;//结算单
    @Bind(R.id.v_evection)
    View v_evection;//下划线
    @Bind(R.id.v_cost)
    View v_cost;
    @Bind(R.id.v_reward)
    View v_reward;
    @Bind(R.id.v_statement)
    View v_statement;
    @Bind(R.id.v_overnight_money)
    View v_overnight_money;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.sv)
    SearchView sv;
    @Bind(R.id.rv)
    RecyclerView rv;
    @Bind(R.id.tv_title)
    TextView tv_title;
    @Bind(R.id.swipe_container)
    SwipeRefreshLayout mSwipeLayout;
    private Context mContext;
    private List<RelativeLayout> ls_rl;
    private List<View> ls_v;
    private List<ReimbursementVoInfo> ls_audit;
    private MyFQAdapter auditAdapter;
    private OkHttpClient mOkHttpClient;
    private List<ReimbursementVoInfo> ls_info,ls_newInfo;
    private String type = "";
    private Intent mIntent;
    private int index;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_my_fq);    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        mContext=this;

        //设置布局管理器
        rv.setLayoutManager(new LinearLayoutManager(mContext));
        rv.setHasFixedSize(true);
        rv.setItemAnimator(new DefaultItemAnimator());

        sv.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        mIntent=getIntent();


        ls_rl= new ArrayList<>();
        ls_rl.add(rl_cost);
        ls_rl.add(rl_evection);
        ls_rl.add(rl_reward);
        ls_rl.add(rl_overnight_money);
        ls_rl.add(rl_statement);

        ls_v=new ArrayList<>();
        ls_v.add(v_cost);
        ls_v.add(v_evection);
        ls_v.add(v_reward);
        ls_v.add(v_overnight_money);
        ls_v.add(v_statement);

        ls_info=new ArrayList<>();
        ls_newInfo = new ArrayList<>();
        ls_audit= new ArrayList<>();
        index=0;

        mSwipeLayout.setOnRefreshListener((SwipeRefreshLayout.OnRefreshListener) mContext);
        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
//        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.PULL_FROM_START);
        mSwipeLayout.setLoadNoFull(false);

    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        for (View v : ls_rl) {
            v.setOnClickListener(new MyFQActivity.mOnClick());
        }
//        setSelection(index);

        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        getdata();
    }

    @Override
    public void onRefresh() {
        refreshdata(index);
    }

    class mOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int i = 0;
            for (View v1 : ls_rl) {
                if (v1.getId() == v.getId()) {
                    setSelection(i);
                    index=i;
                    showdata(index,type);
                }
                i++;
            }
        }
    }

    /**
     *页面回调方法
     *@author Wangzhiqiang
     *Created on 2017/12/19 15:14
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode ==1){
            onRefresh();
        }

    }

    /**
     *选项卡点击动画
     *@author Wangzhiqiang
     *Created on 2017/12/14 12:05
     */
    private void setSelection(int index) {
        for (int i = 0; i < ls_rl.size(); i++) {
            if (i == index) {
                ls_v.get(i).setBackgroundColor(mContext.getResources().getColor(R.color.blue));
            } else {
                ls_v.get(i).setBackgroundColor(mContext.getResources().getColor(R.color.touMing));
            }
        }

    }

    /**
     *获取数据
     *@author Wangzhiqiang
     *Created on 2017/12/21 18:58
     */
    private void getdata(){

        mOkHttpClient = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", 1);
        map.put("pageSize", 1000);
        String json = JSON.toJSONString(map);
        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/selfLaunch")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();

        Call call = mOkHttpClient.newCall(request);
        mSwipeLayout.setRefreshing(true);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mSwipeLayout.setRefreshing(false);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mSwipeLayout.setRefreshing(false);
                String str = response.body().string();
                if(str.indexOf("contentList")>=0) {
                    String msg = JsonUtil.getMsg(str, "contentList");
                    ls_info = JsonUtil.getPersons(msg, new TypeToken<List<ReimbursementVoInfo>>() {
                    }.getType());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for (ReimbursementVoInfo info : ls_info) {
                                if (info.getReimbursementType().equals("expenseCost")) {
                                    ls_newInfo.add(info);
                                }
                            }

                            if (ls_newInfo.size()==0){
                                for (ReimbursementVoInfo info : ls_info) {
                                    if (info.getReimbursementType().equals("travelExpense")) {
                                        ls_newInfo.add(info);
                                    }
                                }
                            }else {
                                index =0;
                                setSelection(index);
                                showdata(index,type);
                                return;
                            }
                            if (ls_newInfo.size()==0){
                                for (ReimbursementVoInfo info : ls_info) {
                                    if (info.getReimbursementType().equals("rewardDeduction")) {
                                        ls_newInfo.add(info);
                                    }
                                }
                            }else {
                                index =1;
                                setSelection(index);
                                showdata(index,type);
                                return;
                            }
                            if (ls_newInfo.size()==0){
                                for (ReimbursementVoInfo info : ls_info) {
                                    if (info.getReimbursementType().equals("borrowing")) {
                                        ls_newInfo.add(info);
                                    }
                                }
                            }else {
                                index =2;
                                setSelection(index);
                                showdata(index,type);
                                return;
                            }
                            if (ls_newInfo.size()==0){
                                for (ReimbursementVoInfo info : ls_info) {
                                    if (info.getReimbursementType().equals("adviceSettlement")) {
                                        ls_newInfo.add(info);
                                    }
                                }

                            }else {
                                index =3;
                                setSelection(index);
                                showdata(index,type);
                                return;
                            }
                            if (ls_newInfo.size()==0){

                                index =0;
                                setSelection(index);
                                showdata(index,type);
                                return;
                            }else {
                                index =4;
                                setSelection(index);
                                showdata(index,type);
                                return;
                            }
                        }
                    });

                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "查询报销单信息出现错误", Toast.LENGTH_SHORT).show();

                        }
                    });
                }
            }
        });

    }
    /**
     *获取数据
     *@author Wangzhiqiang
     *Created on 2017/12/21 18:58
     */
    private void refreshdata(final int index){

        mOkHttpClient = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", 1);
        map.put("pageSize", 1000);
        String json = JSON.toJSONString(map);
        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/selfLaunch")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();

        Call call = mOkHttpClient.newCall(request);
        mSwipeLayout.setRefreshing(true);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mSwipeLayout.setRefreshing(false);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mSwipeLayout.setRefreshing(false);
                String str = response.body().string();
                if(str.indexOf("contentList")>=0) {
                    String msg = JsonUtil.getMsg(str, "contentList");
                    ls_info = JsonUtil.getPersons(msg, new TypeToken<List<ReimbursementVoInfo>>() {
                    }.getType());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            showdata(index,type);
                        }
                    });

                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "查询报销单信息出现错误", Toast.LENGTH_SHORT).show();

                        }
                    });
                }
            }
        });

    }
    /**
     *数据分类
     *@author Wangzhiqiang
     *Created on 2017/12/21 21:23
     */
    private void showdata(int index,String type)
    {
        ls_newInfo.clear();

            if (index == 0) {
                for (ReimbursementVoInfo info : ls_info) {
                    if (info.getReimbursementType().equals("expenseCost")) {
                        ls_newInfo.add(info);
                    }
                }
            } else if (index == 1) {
                for (ReimbursementVoInfo info : ls_info) {
                    if (info.getReimbursementType().equals("travelExpense")) {
                        ls_newInfo.add(info);
                    }
                }
            } else if (index == 2) {
                for (ReimbursementVoInfo info : ls_info) {
                    if (info.getReimbursementType().equals("rewardDeduction")) {
                        ls_newInfo.add(info);
                    }
                }
            } else if (index == 3) {
                for (ReimbursementVoInfo info : ls_info) {
                    if (info.getReimbursementType().equals("borrowing")) {
                        ls_newInfo.add(info);
                    }
                }
            } else if (index == 4) {
                for (ReimbursementVoInfo info : ls_info) {
                    if (info.getReimbursementType().equals("adviceSettlement")) {
                        ls_newInfo.add(info);
                    }
                }
        }
        if(ls_newInfo.size()==0){
            Toast.makeText(mContext, "暂无报销单信息", Toast.LENGTH_SHORT).show();
        }
        showRecyclerViewData(index,type);
    }


    /**
     *显示数据
     *@author Wangzhiqiang
     *Created on 2017/12/22 9:41
     */
    private void showRecyclerViewData(final int index,final String type){

        ls_audit.clear();
        ls_audit.addAll(ls_newInfo);

        if(auditAdapter==null){
            auditAdapter=new MyFQAdapter(ls_audit,mContext);
            rv.setAdapter(auditAdapter);
        }else{
            auditAdapter.notifyDataSetChanged();
        }

        auditAdapter.setOnRecyclerViewListener(new MyFQAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if (index==4){
                    ReimbursementVoInfo info = ls_audit.get(position);
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), SettlementAuditActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("ReimbursementVoInfo",info);
                    intent.putExtra("type","1");
                    intent.putExtra("who","1");
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                }else {
                    ReimbursementVoInfo info = ls_audit.get(position);
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), AuditDetailActivity.class);
                    Bundle bundle = new Bundle();
                    intent.putExtra("who","1");
                    bundle.putSerializable("ReimbursementVoInfo",info);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                }

            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

    }
}

